package net.xdclass.xdclassmq.controller;

import net.xdclass.xdclassmq.config.RocketMqConfig;
import net.xdclass.xdclassmq.jms.producer.OrderProducer;
import net.xdclass.xdclassmq.model.JsonData;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author whg
 * @create 2023/1/3 10:02
 * @description：
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderProducer orderProducer;

    @Autowired
    private RocketMqConfig rocketMqConfig;


    @GetMapping("send")
    public Object send(String text) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message message = new Message(rocketMqConfig.getOrderTopic(),
                "tag_order","6688",("this is " + text).getBytes());
        SendResult sendResult = orderProducer.getProducer().send(message);
        System.out.println(sendResult);
        return JsonData.buildSuccess(sendResult);
    }

    /**
     * 异步发送
     * @param text
     * @return
     * @throws InterruptedException
     * @throws RemotingException
     * @throws MQClientException
     * @throws MQBrokerException
     */
    @GetMapping("send_async")
    public Object async(String text) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        Message message = new Message(rocketMqConfig.getOrderTopic(),
                "tag_order","66881",("this is " + text).getBytes());
        orderProducer.getProducer().send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.printf("发送结果=s%，msg=s%",
                        sendResult.getSendStatus(),
                        sendResult.toString());
            }

            @Override
            public void onException(Throwable e) {
                e.printStackTrace();
            }
        });
        return JsonData.buildSuccess();
    }
}
